using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// UI界面逻辑类。
/// </summary>
public abstract class UIFormLogic : MonoBehaviour
{
    private bool m_Available = false;
    private bool m_Visible = false;
    private UIForm m_UIForm = null;
    private Transform m_CachedTransform = null;
    private int m_OriginalLayer = 0;
    private Vector3 m_OutPos = new Vector3(-1500, 0, 0);

    protected object UserData;

    // 事件注册列表，用于自动管理事件生命周期
    private List<RegisteredEvent> m_RegisteredEvents = new List<RegisteredEvent>();

    /// <summary>
    /// 已注册的事件信息
    /// </summary>
    private class RegisteredEvent
    {
        public int EventId { get; }
        public EventHandler<GameEventArgs> Handler { get; }

        public RegisteredEvent(int eventId, EventHandler<GameEventArgs> handler)
        {
            EventId = eventId;
            Handler = handler;
        }
    }

    /// <summary>
    /// 获取界面。
    /// </summary>
    public UIForm UIForm
    {
        get
        {
            return m_UIForm;
        }
    }

    /// <summary>
    /// 获取或设置界面名称。
    /// </summary>
    public string Name
    {
        get
        {
            return gameObject.name;
        }
        set
        {
            gameObject.name = value;
        }
    }

    /// <summary>
    /// 获取界面是否可用。
    /// </summary>
    public bool Available
    {
        get
        {
            return m_Available;
        }
    }

    /// <summary>
    /// 获取或设置界面是否可见。
    /// </summary>
    public bool Visible
    {
        get
        {
            return m_Available && m_Visible;
        }
        set
        {
            if (!m_Available)
            {
                Logger.LogWarning("UI form '{0}' is not available.", Name);
                return;
            }

            if (m_Visible == value)
            {
                return;
            }

            m_Visible = value;
            InternalSetVisible(value);
        }
    }

    /// <summary>
    /// 获取已缓存的 Transform。
    /// </summary>
    public Transform CachedTransform
    {
        get
        {
            return m_CachedTransform;
        }
    }

    /// <summary>
    /// 初始化界面。
    /// </summary>
    /// <param name="userData">用户自定义数据。</param>
    protected internal virtual void OnInit(object userData)
    {
        if (m_CachedTransform == null)
        {
            m_CachedTransform = transform;
        }

        m_UIForm = GetComponent<UIForm>();
        m_OriginalLayer = gameObject.layer;
    }

    /// <summary>
    /// 预加载界面。
    /// </summary>
    /// <param name="userData">用户自定义数据。</param>
    protected internal virtual void OnPreload(object userData)
    {
    }

    /// <summary>
    /// 回收界面。
    /// </summary>
    protected internal virtual void OnRecycle()
    {
        // 销毁时移除所有注册的事件
        UnregisterAllEvents();
    }

    /// <summary>
    /// 打开界面。
    /// </summary>
    /// <param name="userData">用户自定义数据。</param>
    protected internal virtual void OnOpen(object userData)
    {
        UserData = userData;
        m_Available = true;
        Visible = true;
    }

    /// <summary>
    /// 关闭界面。
    /// </summary>
    /// <param name="isShutdown">是否是关闭游戏时触发。</param>
    /// <param name="userData">用户自定义数据。</param>
    protected internal virtual void OnClose(bool isShutdown, object userData)
    {
        // 自动移除所有注册的事件
        UnregisterAllEvents();
        
        gameObject.SetLayerRecursively(m_OriginalLayer);
        Visible = false;
        m_Available = false;
    }

    /// <summary>
    /// 暂停界面。
    /// </summary>
    protected internal virtual void OnPause()
    {
        // 暂停/隐藏时移除所有注册的事件
        UnregisterAllEvents();
        
        // var formName = Path.GetFileNameWithoutExtension(UIForm.UIFormAssetName);
        // if (formName.Equals("MainPage"))
        //     CachedTransform.localPosition = m_OutPos;
        // else
        Visible = false;
    }

    /// <summary>
    /// 暂停界面恢复。
    /// </summary>
    protected internal virtual void OnResume()
    {
        // var formName = Path.GetFileNameWithoutExtension(UIForm.UIFormAssetName);
        // if (formName.Equals("MainPage"))
        //     CachedTransform.localPosition = Vector3.zero;
        // else
        Visible = true;
    }

    /// <summary>
    /// 界面被遮挡。
    /// </summary>
    protected internal virtual void OnCover()
    {
        // 被覆盖/隐藏时移除所有注册的事件
        UnregisterAllEvents();
    }

    /// <summary>
    /// 界面遮挡恢复。
    /// </summary>
    protected internal virtual void OnReveal()
    {
        Visible = true;
    }

    /// <summary>
    /// 界面激活。
    /// </summary>
    /// <param name="userData">用户自定义数据。</param>
    protected internal virtual void OnRefocus(object userData)
    {
    }

    /// <summary>
    /// 界面轮询。
    /// </summary>
    /// <param name="elapseSeconds">逻辑流逝时间，以秒为单位。</param>
    /// <param name="realElapseSeconds">真实流逝时间，以秒为单位。</param>
    protected internal virtual void OnUpdate(float elapseSeconds, float realElapseSeconds)
    {
    }

    /// <summary>
    /// 界面深度改变。
    /// </summary>
    /// <param name="uiGroupDepth">界面组深度。</param>
    /// <param name="depthInUIGroup">界面在界面组中的深度。</param>
    protected internal virtual void OnDepthChanged(int uiGroupDepth, int depthInUIGroup)
    {
    }

    /// <summary>
    /// 设置界面的可见性。
    /// </summary>
    /// <param name="visible">界面的可见性。</param>
    protected virtual void InternalSetVisible(bool visible)
    {
        gameObject.SetActive(visible);
    }

    /// <summary>
    /// 前面的界面已经被关闭，当前界面重新回到当前 Group 的第一层时。
    /// </summary>
    public virtual void OnReFirst()
    {
    }

    #region 事件注册管理

    /// <summary>
    /// 注册事件。
    /// </summary>
    /// <param name="eventType">事件类型。</param>
    /// <param name="handler">事件处理器。</param>
    protected void RegisterEvent(EventType eventType, EventHandler<GameEventArgs> handler)
    {
        if (handler == null)
        {
            Logger.LogError("Event handler is null.");
            return;
        }

        int eventId = (int)eventType;
        EventHelper.Subscribe(eventId, handler);
        m_RegisteredEvents.Add(new RegisteredEvent(eventId, handler));
    }

    /// <summary>
    /// 注册事件（使用事件ID）。
    /// </summary>
    /// <param name="eventId">事件ID。</param>
    /// <param name="handler">事件处理器。</param>
    protected void RegisterEvent(int eventId, EventHandler<GameEventArgs> handler)
    {
        if (handler == null)
        {
            Logger.LogError("Event handler is null.");
            return;
        }

        EventHelper.Subscribe(eventId, handler);
        m_RegisteredEvents.Add(new RegisteredEvent(eventId, handler));
    }

    /// <summary>
    /// 移除事件。
    /// </summary>
    /// <param name="eventType">事件类型。</param>
    /// <param name="handler">事件处理器。</param>
    protected void UnregisterEvent(EventType eventType, EventHandler<GameEventArgs> handler)
    {
        if (handler == null)
        {
            return;
        }

        int eventId = (int)eventType;
        EventHelper.Unsubscribe(eventId, handler);
        m_RegisteredEvents.RemoveAll(e => e.EventId == eventId && e.Handler == handler);
    }

    /// <summary>
    /// 移除事件（使用事件ID）。
    /// </summary>
    /// <param name="eventId">事件ID。</param>
    /// <param name="handler">事件处理器。</param>
    protected void UnregisterEvent(int eventId, EventHandler<GameEventArgs> handler)
    {
        if (handler == null)
        {
            return;
        }

        EventHelper.Unsubscribe(eventId, handler);
        m_RegisteredEvents.RemoveAll(e => e.EventId == eventId && e.Handler == handler);
    }

    /// <summary>
    /// 移除所有注册的事件。
    /// </summary>
    private void UnregisterAllEvents()
    {
        foreach (var registeredEvent in m_RegisteredEvents)
        {
            try
            {
                EventHelper.Unsubscribe(registeredEvent.EventId, registeredEvent.Handler);
            }
            catch (System.Exception e)
            {
                Logger.LogErrorFormat("Unregister event error: {0}", e.Message);
            }
        }

        m_RegisteredEvents.Clear();
    }

    #endregion
}
